#include "randnum.h"
#include <windows.h>
#include <sortthread.h>
#include <iostream>
using namespace std;

/*堆排序函数*/
/*传入参数**SortObject结构体***/
/*使用sift辅助函数*/
void SortThread::heapSort(SortObject *pvector)
{
    sortTle = 0;
    sortMov = 0;
    sortCmp = 0;
    int i, n;
    RecordNode temp;
    n = this->size;
    for (i = n / 2; i >= 0; i--)
    {
        catched1 = i;
        sift(pvector, n, i);
        for(int ii =0; ii < this->size; ii++)
        {
            this->sendArray[ii] = pvector->record[ii].key;
        }
        this->senda(catched1,-1);
    }
    for (i = n - 1; i > 0; i--)
    {
        catched1 = i;
        this->senda(catched1,-1);
        temp = pvector->record[0];
        pvector->record[0] = pvector->record[i];
        pvector->record[i] = temp;
        sift(pvector, i, 0);
        //Sleep(frd);
        for(int ii =0; ii < this->size; ii++)
        {
            catched1 = i;
            this->sendArray[ii] = pvector->record[ii].key;
        }
        this->senda(catched1,-1);
    }
    for(int i = 0; i < size; i++)
    {
        senda(i,-10);
    }
}

/*堆排序建堆辅助函数*/
void SortThread::sift(SortObject *pvector, int size, int p)
{
    sortCmp++;
    this->sendt(sortTle,sortMov,sortCmp);
    sortTle++;
    this->sendt(sortTle,sortMov,sortCmp);
    this->senda(catched1,-1);
    RecordNode temp = pvector->record[p];
    int child = 2 * p + 1;
    while (child < size)
    {
        sortCmp++;
        this->sendt(sortTle,sortMov,sortCmp);
        //Sleep(frd);
        for(int ii =0; ii < this->size; ii++)
        {
            catched1 = child;
            this->sendArray[ii] = pvector->record[ii].key;
        }
        this->senda(catched1,-1);
        if ((child < size - 1) && (pvector->record[child].key < pvector->record[child + 1].key))
        {
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            //Sleep(frd);
            for(int ii =0; ii < this->size; ii++)
            {
                catched1 = child;
                this->sendArray[ii] = pvector->record[ii].key;
            }
            this->senda(catched1,-1);
            sortMov++;
            this->sendt(sortTle,sortMov,sortCmp);
            child++;
        }
        if (temp.key < pvector->record[child].key)
        {
            sortCmp++;
            this->sendt(sortTle,sortMov,sortCmp);
            //Sleep(frd);
            for(int ii =0; ii < this->size; ii++)
            {
                catched1 = child;
                this->sendArray[ii] = pvector->record[ii].key;
            }
            this->senda(catched1,-1);
            sortMov++;
            this->sendt(sortTle,sortMov,sortCmp);
            pvector->record[p] = pvector->record[child];
            p = child;
            child = 2 * p + 1;
        }
        else
        {
            catched1 = child;
            break;
        }
    }
    pvector->record[p] = temp;
}

